﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Liang.Device.Camera.Const;
using Liang.Device.Camera.Dll;
using Liang.Device.Model.Camera;
using System.Runtime.InteropServices;

namespace Liang.Device.Camera.Action
{
    /// <summary>
    /// 爱普视达摄像头
    /// </summary>
    public sealed class AipStarCamera : ICamera<AipStar>
    {
        /// <summary>
        /// 静态只读实例，创建对象实例的唯一地方，加上只读属性可保证线程安全
        /// </summary>
        private static readonly AipStarCamera _instance = new AipStarCamera();

        /// <summary>
        /// 获取当前对象实例的唯一入口
        /// </summary>
        public static AipStarCamera Instance
        {
            get { return _instance; }
        }

        /// <summary>
        /// 判断摄像头是否已初始化SDK
        /// </summary>
        /// 
        private static bool isSDKInited = false;

        /// <summary>
        /// SDK是否已初始化
        /// </summary>
        public static bool IsSDKInited
        {
            get { return AipStarCamera.isSDKInited; }
            set { AipStarCamera.isSDKInited = value; }
        }

        /// <summary>
        /// 静态构造函数，在这里初始化摄像头SDK，仅调用一次
        /// </summary>
        static AipStarCamera()
        {
            try
            {
                AipStarCamera.IsSDKInited = AipStarDll.KsCamera_AipStar_InitSDK();
            }
            catch (Exception e)
            {
                throw new CameraException("无法初始化摄像头SDK", e.Message);
            }
        }

        private AipStarCamera()
        {

        }

        /// <summary>
        /// 析构函数
        /// <para>在析构函数内部，将会注销SDK</para>
        /// </summary>
        ~AipStarCamera()
        {
            if (IsSDKInited)
            {
                try
                {
                    AipStarDll.KsCamera_AipStar_CleanupSDK();
                }
                catch (Exception e)
                {
                    throw new CameraException("无法注销摄像头SDK", e.Message);
                }
            }
        }

        /// <summary>
        /// 打开摄像头
        /// </summary>
        /// <param name="cameraParam"></param>
        /// <returns></returns>
        public bool Open(AipStar cameraParam)
        {
            //if (!cameraParam.OpenForCaptureOnly)
            {
                // 打开播放句柄
                try
                {
                    cameraParam.DevViewHandle = AipStarDll.KsCamera_AipStar_Login((uint)AipStarInitModel.TMCC_INITTYPE_REALSTREAM);
                    if (IntPtr.Zero == cameraParam.DevViewHandle)
                    {
                        return false;
                    }
                }
                catch (Exception e)
                {
                    throw new CameraException("无法登陆摄像头", e.Message);
                }
            }

            // 打开控制句柄
            return OpenForCaptureOnly(cameraParam);
        }

        /// <summary>
        /// 只抓拍，不预览视频
        /// </summary>
        /// <param name="cameraParam"></param>
        /// <returns></returns>
        public bool OpenForCaptureOnly(AipStar cameraParam)
        {
            try
            {
                // 打开控制及抓拍句柄
                cameraParam.DevControlHandle = AipStarDll.KsCamera_AipStar_Login((uint)AipStarInitModel.TMCC_INITTYPE_CONTROL);

                if (IntPtr.Zero != cameraParam.DevControlHandle)
                {
                    // 连接控制
                    if (!AipStarDll.KsCamera_AipStar_Connect(cameraParam.DevControlHandle,
                        cameraParam.Ipaddr, cameraParam.Port,
                        cameraParam.Accesscout, cameraParam.Password,
                        true))
                    {
                        return false;
                    }

                    // 设置摄像头参数
                    //return SetCamera(obj);
                    return SetCameraEx(cameraParam);
                    //return true;
                }
            }
            catch (Exception e)
            {
                throw new CameraException("无法登陆摄像头", e.Message);
            }

            return false;
        }

        /// <summary>
        /// 播放视频
        /// </summary>
        /// <param name="cameraParam"></param>
        /// <returns></returns>
        public bool Play(AipStar cameraParam)
        {
            if (IntPtr.Zero == cameraParam.DevViewHandle)
            {
                return false;
            }

            bool bSuccessed = false;

            try
            {
                bSuccessed = AipStarDll.KsCamera_AipStar_Play(
                    cameraParam.DevViewHandle, cameraParam.PlayWindow,
                    cameraParam.Ipaddr, cameraParam.Port,
                    cameraParam.Accesscout, cameraParam.Password,
                    (ushort)cameraParam.Channel, cameraParam.Stream);
            }
            catch (Exception e)
            {
                throw new CameraException("无法播放摄像头", e.Message);
            }

            return bSuccessed;
        }

        /// <summary>
        /// 停止播放
        /// </summary>
        /// <param name="cameraParam"></param>
        /// <returns></returns>
        public bool Stop(AipStar cameraParam)
        {
            try
            {
                AipStarDll.KsCamera_AipStar_StopPlay(cameraParam.DevViewHandle);
            }
            catch (Exception e)
            {
                throw new CameraException("无法停止播放", e.Message);
            }

            return true;
        }

        /// <summary>
        /// 关闭摄像头
        /// </summary>
        /// <param name="cameraParam"></param>
        /// <returns></returns>
        public bool Close(AipStar cameraParam)
        {
            try
            {
                // 关闭控制句柄
                AipStarDll.KsCamera_AipStar_DisConnect(cameraParam.DevControlHandle);
                cameraParam.DevControlHandle = IntPtr.Zero;

                // 关闭预览句柄
                AipStarDll.KsCamera_AipStar_Logout(cameraParam.DevViewHandle);
                cameraParam.DevViewHandle = IntPtr.Zero;
            }
            catch (Exception e)
            {
                throw new CameraException("无法关闭摄像头", e.Message);
            }

            return true;
        }

        /// <summary>
        /// 抓拍图片
        /// </summary>
        /// <param name="cameraParam"></param>
        /// <param name="strImageFile"></param>
        /// <returns></returns>
        public bool Capture(AipStar cameraParam, string strImageFile)
        {
            if (IntPtr.Zero == cameraParam.DevControlHandle)
            {
                return false;
            }

            bool bSuccessed = false;

            try
            {
                if (cameraParam.RealCapture)
                {
                    bSuccessed = AipStarDll.KsCamera_AipStar_RealCapture(cameraParam.DevControlHandle, (byte)cameraParam.Channel, cameraParam.Stream, strImageFile);
                }
                else
                {
                    bSuccessed = AipStarDll.KsCamera_AipStar_Capture(cameraParam.DevViewHandle, strImageFile);
                }
                
            }
            catch (Exception e)
            {
                throw new CameraException("摄像头抓拍失败", e.Message);
            }

            return bSuccessed;
        }

        /// <summary>
        /// 设置摄像头参数
        /// </summary>
        /// <param name="cameraParam"></param>
        /// <returns></returns>
        public bool SetCamera(AipStar cameraParam)
        {
            bool bSuccessed = false;
            try
            {
                if (IntPtr.Zero != cameraParam.DevControlHandle)
                {
                    bSuccessed = AipStarDll.KsCamera_AipStar_CameraVideoCfg(
                        cameraParam.DevControlHandle,
                        (byte)cameraParam.Channel, cameraParam.Stream,
                        cameraParam.Resolution, cameraParam.ColorTransMode, cameraParam.ShutterSpeed);
                }
            }
            catch (Exception e)
            {
                throw new CameraException("设置摄像头参数失败", e.Message);
            }

            return bSuccessed;
        }

        /// <summary>
        /// 设置摄像头参数
        /// </summary>
        /// <param name="cameraParam"></param>
        /// <returns></returns>
        public bool SetCameraEx(AipStar cameraParam)
        {
            bool bSuccessed = false;

            try
            {
                if (IntPtr.Zero != cameraParam.DevControlHandle)
                {
                    tmVideoInCfg_t t = new tmVideoInCfg_t();
                    int size = Marshal.SizeOf(typeof(tmVideoInCfg_t));
                    t.dwSize = (uint)size;
                    IntPtr tPtr = Marshal.AllocHGlobal(Marshal.SizeOf(t));
                    Marshal.StructureToPtr(t, tPtr, true);

                    // 先获取配置
                    bSuccessed = AipStarDll.KsCamera_AipStar_GetConfig(cameraParam.DevControlHandle,
                        (byte)cameraParam.Channel, cameraParam.Stream, tPtr, size, size, 
                        ControlCommand.TMCC_MAJOR_CMD_VIDEOINCFG, ControlCommand.TMCC_MINOR_CMD_VIDEOIN);

                    // 再修改配置
                    if (bSuccessed)
                    {
                        t = (tmVideoInCfg_t)Marshal.PtrToStructure(tPtr, typeof(tmVideoInCfg_t));

                        // 色彩模式
                        t.byColorTransMode = cameraParam.ColorTransMode;
                        // 快门
                        t.byShutterSpeed = cameraParam.ShutterSpeed;
                        // 增益
                        t.byAgc = cameraParam.Agc;

                        Marshal.StructureToPtr(t, tPtr, true);

                        bSuccessed = AipStarDll.KsCamera_AipStar_SetConfig(cameraParam.DevControlHandle,
                        (byte)cameraParam.Channel, cameraParam.Stream, tPtr, size, size,
                        ControlCommand.TMCC_MAJOR_CMD_VIDEOINCFG, ControlCommand.TMCC_MINOR_CMD_VIDEOIN);
                    }

                    Marshal.FreeHGlobal(tPtr);
                }
            }
            catch (Exception e)
            {
                throw new CameraException("设置摄像头参数失败", e.Message);
            }

            return bSuccessed;
        }
    }
}
